package org.shaka.db.sqlbuilder.sql;

import java.util.Iterator;
import java.util.List;

import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;

public class SqlConditions extends SqlCondition {
    private String linkStr;
    private List<SqlCondition> conditions;

    private SqlConditions(String linkStr) {
        this.linkStr = linkStr;
        conditions = Lists.newArrayList();
    }

    public static SqlConditions and(SqlCondition... conditions) {
        return new SqlConditions(" AND ").addCondition(conditions);
    }

    public static SqlConditions or(SqlCondition... conditions) {
        return new SqlConditions(" OR ").addCondition(conditions);
    }

    public SqlConditions addCondition(SqlCondition... conditions) {
        for (SqlCondition sqlCondition : conditions) {
            this.conditions.add(sqlCondition);
        }
        return this;
    }

    public void conditionsPartial(StringBuilder sb) {
        sb.append("(");
        Iterator<String> iter = Iterators.transform(conditions.iterator(), new Function<SqlCondition, String>() {
            @Override
            public String apply(SqlCondition input) {
                return input.conditionsPartial();
            }
        });
        if (iter.hasNext()) {
            sb.append(iter.next());
            while (iter.hasNext()) {
                sb.append(linkStr).append(iter.next());
            }
        }
        sb.append(")");
    }

    public String conditionsPartial() {
        StringBuilder sb = new StringBuilder();
        conditionsPartial(sb);
        return sb.toString();
    }

    public boolean hasParams() {
        for (SqlCondition sqlCondition : conditions) {
            if (sqlCondition.hasParams())
                return true;
        }
        return false;
    }

    public List<Object> getParams() {
        List<Object> result = Lists.newArrayList();
        for (SqlCondition sqlCondition : conditions) {
            result.addAll(sqlCondition.getParams());
        }
        return result;
    }
}
